/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

let { ipcRenderer, shell } = require('electron');
let { helpDocUrl } = require('../../../../../../../product.json');
let { setLanguage, getLanguage, setDarkTheme, checkhttp } = require('../../utils/utils.js');
let utils = require('../../utils/utils.js');
let fs = require('fs');
let path = require('path');
let compare = require('./compare');
let streamArgs;
let isFirstLoad;
const logger = require('./logger'); // 导入logger.js中的logger对象
const verify = require('./verifySign');
let addNewPage = 0;
let extAddressPath;
var updatedst = utils.configDir() + "/" + getDataDir();
var onlineInstallTabArray = ["first", "waitTab", "onlineInstallTab1", "onlineInstallTab2", "onlineInstallTab3", "onlineInstallTab4"];
var onlineInstallTabArrayIndex = 0;
var justDownLoadTabArray = ["first", "waitTab", "justDownloadTab2", "justDownloadTab3", "justDownloadTab4", "justDownloadTab5"];
var justDownLoadTabArrayIndex = 0;
var localInstallTabArray = ["first", "localInstallTab1", "localInstallTab2", "localInstallTab3", "localInstallTab4", "localInstallTab5"];
var localInstallTabArrayIndex = 0;
var firstClassList;

//用来标识程序结束完成
var gExtDownNum = 0;
var gSoftInstNum = 0;
var gExtInst = 0;

let extInstallState = new Map();
let extMap = {};
let extDownloadDoneCounter = 0;
let extInstallDoneCounter = 0;
let logShow = 0;
let progressNum = 0;
/**
 * 窗口关闭按钮动作
 */
document.getElementById('closeBtn').addEventListener('click', () => {
	if (onlineInstallRadio.checked &&
		onlineInstallTabArray[onlineInstallTabArrayIndex] == "onlineInstallTab4" &&
		document.getElementById('cancel').disabled == false) {
		ipcRenderer.send('kylinide.installWizard.show', { type: "info", message: "正在进行安装操作，若关闭窗口，则需先点击取消按钮中断安装过程。", title: "提示" });
		//检查是否有进程正在安装，如果是，则提醒用户先点击取消安装，停止后台程序。然后再关闭程序
		// ipcRenderer.send('kylinide.installWizard.closeBefore', { type: "processterm" });
	}
	else {
		ipcRenderer.send('kylinide.installWizard.closeWizard', { type: "close" });
		removeAllListeners();
	}


});

document.getElementById('helpLink').addEventListener('click', (e) => {
	e.preventDefault();
	shell.openExternal(helpDocUrl);
});

document.getElementById('skipAll').addEventListener('click', () => {
	ipcRenderer.send('kylinide.installWizard.skipWizard');
});

document.getElementById('prevStep').addEventListener('click', () => {
	Prev(-1);
});

document.getElementById('nextStep').addEventListener('click', () => {
	console.log('click nextStep');
	nextPrev(1);
});

document.getElementById('selectConfigPath').addEventListener('click', () => {
	console.log('get configPath');
	ipcRenderer.send('kylinide.installWizard.justDownLoad', { type: "getPath" });
});
document.getElementById('cancel').addEventListener('click', () => {
	console.log('cancel');
	// ipcRenderer.removeAllListeners('kylinide.installWizard.msg');
	ipcRenderer.send('kylinide.installWizard.msg.process', { type: "cancel" });
});


// 添加点击事件监听器
let finishFlag = -1;
document.getElementById("switchInstallOutput").addEventListener("click", function () {
	// 切换显示和隐藏
	const logPreElement = document.getElementById("installLogPre");
	const installPreElement = document.getElementById("detailInstallPre");
	const extLogPreElement = document.getElementById("extInstallLogPre");
	const finishPage = document.getElementById("finishPage");
	let logView = [logPreElement, extLogPreElement, installPreElement, finishPage];
	logShow++;
	if (logShow % (logView.length + finishFlag) == 0) {
		installPreElement.style.display = "block";
		logPreElement.style.display = "none";
		extLogPreElement.style.display = "none";
		if (finishFlag > -1)
			finishPage.style.display = "none";
	}
	else if (logShow % (logView.length + finishFlag) == 1) {
		installPreElement.style.display = "none";
		logPreElement.style.display = "block";
		extLogPreElement.style.display = "none";
		if (finishFlag > -1)
			finishPage.style.display = "none";
	}
	else if (logShow % (logView.length + finishFlag) == 2) {
		installPreElement.style.display = "none";
		logPreElement.style.display = "none";
		extLogPreElement.style.display = "block";
		if (finishFlag > -1)
			finishPage.style.display = "none";
	} else if (logShow % (logView.length + finishFlag) == 3) {
		finishPage.style.display = "block";
		installPreElement.style.display = "none";
		logPreElement.style.display = "none";
		extLogPreElement.style.display = "none";
	}

});

const onlineInstallRadio = document.getElementById("onlineInstall");
const localInstallRadio = document.getElementById("localInstall");
const justDownloadRadio = document.getElementById("justDownload");
const notNowRadio = document.getElementById("notNow");

//设置国际化显示语言
function setDisplayLanguage() {
	document.getElementById('title').innerText = setLanguage('title');
	document.getElementById('helpLink').innerText = setLanguage('helpLink');
	document.getElementById('skipAll').innerText = setLanguage('skipAll');
	document.getElementById('prevStep').innerText = setLanguage('prevStep');
	document.getElementById('nextStep').innerText = setLanguage('nextStep');
	document.getElementById('onlineInstalllabel').innerText = setLanguage('onlineInstalllabel');
	document.getElementById('lablenotNow').innerText = setLanguage('lablenotNow');
	document.getElementById("localInstall").innerText = setLanguage('localInstall');
	document.getElementById("justDownload").innerText = setLanguage('justDownload');
	document.getElementById('cancel').innerText = setLanguage('cancel');
	document.getElementById('cancel').style.display = "none";
	// document.getElementById("confirm").innerText = setLanguage('okStep');
}

ipcRenderer.on('init-data', (event, arg) => {
	//TODO 设置国际化语言
	setDisplayLanguage();
	//封装数据
	streamArgs = {
		isFirstLoad: isFirstLoad,
		...arg,
	};
	isFirstLoad = arg.isFirstLoad;
	if (!isFirstLoad) {
		notNowRadio.style.display = 'none';
		document.getElementById('lablenotNow').style.display = 'none';
	}
	console.log('init-data', JSON.stringify(arg));
	//设置主题
	setDarkTheme(streamArgs);
});

ipcRenderer.on('kylinide.installWizard.init', (event, msg) => {

	if (msg.type === "configVersify") {
		console.log("kylinide.installWizard.init configVersify ");
		if (msg.selectPageShow) {
			const onlineUpdateConfig = document.getElementById("onlineUpdateConfig");
			const onlineLocalConfig = document.getElementById("onlineLocalConfig");
			const parentdiv = document.getElementById('onlinewarning')
			parentdiv.innerHTML = "";
			if (msg.selectPageShow == 1) {
				onlineLocalConfig.disabled = true;
				onlineUpdateConfig.checked = true;
				parentdiv.innerHTML = msg.message;
			} else if (msg.selectPageShow == 2 || msg.selectPageShow == 3) {
				onlineLocalConfig.checked = true;
				onlineUpdateConfig.disabled = true;
				parentdiv.innerHTML = msg.message;
			} else if (msg.selectPageShow == 4) {
				onlineUpdateConfig.checked = true;
			}
		}
		document.getElementById('prevStep').disabled = false;
		document.getElementById('nextStep').disabled = false;
		nextPrev(1);
	} else if (msg.type === "osinfo") {
		console.log("ipcRenderer osinfo ");
		readOSInfo(msg.osinfo);
	} else if (msg.type === "configGetValue") {

		gExtDownNum = 0;
		gSoftInstNum = 0;
		gExtInst = 0;
		progressNum = 0;

		let depPath = msg.depInfoJsonPath;
		let selectAll = document.getElementById("selectAll");
		if (selectAll === null)
			setFisrtClass(depPath, msg.selectKey);
		extAddressPath = msg.extAddressPath;


		let checkboxForm = document.getElementById("checkboxForm");
		//设置下一步按钮显示状态
		let selectedCheckboxes = checkboxForm.querySelectorAll('input[type="checkbox"]:checked');
		console.log("aaa+" + selectedCheckboxes.length);
		if (selectedCheckboxes && selectedCheckboxes.length > 1) {
			document.getElementById("nextStep").disabled = false;
		} else {
			document.getElementById("nextStep").disabled = true;
		}

	} else if (msg.type === "finish") {
		document.getElementById('nextStep').innerText = setLanguage('finish');
		document.getElementById('nextStep').style.disabled = false;
	}
});

ipcRenderer.on('kylinide.installWizard.justDownLoad', (event, msg) => {
	if (msg.type === "configVersify") {
		console.log("kylinide.installWizard.justDownLoad configVersify ");
		if (msg.selectPageShow) {
			const downloadUpdateConfig = document.getElementById("downloadUpdateConfig");
			const downloadlocalConfig = document.getElementById("downloadlocalConfig");
			const parentdiv = document.getElementById('downloadwarning')
			parentdiv.innerHTML = "";
			if (msg.selectPageShow == 1) {
				downloadlocalConfig.disabled = true;
				downloadUpdateConfig.checked = true;
				parentdiv.innerHTML = msg.message;
			} else if (msg.selectPageShow == 2 || msg.selectPageShow == 3) {
				downloadlocalConfig.checked = true;
				downloadUpdateConfig.disabled = true;
				parentdiv.innerHTML = msg.message;
			} else if (msg.selectPageShow == 4) {
				downloadUpdateConfig.checked = true;
			}
		}
		document.getElementById('prevStep').disabled = false;
		document.getElementById('nextStep').disabled = false;
		nextPrev(1);
	} else if (msg.type === "osinfo") {
		//wait
		console.log("ipcRenderer osinfo ");
	}
	if (msg.type === 'getPath') {
		console.log(msg.selectPath);
		document.getElementById("selectPathInput").value = msg.selectPath;
	}
});
function showTabFromIndex(tabArray, Index) {
	let tab = document.getElementById(tabArray[Index]);
	tab.style.display = 'flex';
	if (Index === 0) {
		document.getElementById('prevStep').style.display = 'none';
	} else {
		document.getElementById('prevStep').style.display = 'inline';
	}
	if (Index === (tabArray.length - 1)) {
		document.getElementById('nextStep').innerHTML = setLanguage('okStep');
	} else {
		document.getElementById('nextStep').innerHTML = setLanguage('nextStep');
	}
	if (Index === 0) {
		removeStepIndicator();
	}
	if (Index > 0) {
		fixStepIndicator(Index - 1);
	}

}

let currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
	// This function will display the specified tab of the form...
	let x = document.getElementsByClassName('tab');
	x[n].style.display = 'flex';

	//... and fix the Previous/Next buttons:
	if (n === 0) {
		document.getElementById('prevStep').style.display = 'none';
	} else {
		document.getElementById('prevStep').style.display = 'inline';
	}
	if (n === (x.length - 1)) {
		document.getElementById('nextStep').innerHTML = setLanguage('okStep');
	} else {
		document.getElementById('nextStep').innerHTML = setLanguage('nextStep');
	}
	//... and run a function that will display the correct step indicator:
	// fixStepIndicator(n);
}
function Prev(n) {
	if (onlineInstallRadio.checked) {
		let tab = document.getElementById(onlineInstallTabArray[onlineInstallTabArrayIndex]);
		tab.style.display = 'none';
		onlineInstallTabArrayIndex = onlineInstallTabArrayIndex + n;
		if (onlineInstallTabArray[onlineInstallTabArrayIndex] === 'waitTab') {
			document.getElementById('waitTab').style.display = 'none';
			onlineInstallTabArrayIndex = onlineInstallTabArrayIndex + n;
		}
		if (onlineInstallTabArray[onlineInstallTabArrayIndex] === 'onlineInstallTab2') {
			document.getElementById('nextStep').disabled = false;
		}
		showTabFromIndex(onlineInstallTabArray, onlineInstallTabArrayIndex);
	} else if (justDownloadRadio.checked) {
		let tab = document.getElementById(justDownLoadTabArray[justDownLoadTabArrayIndex]);
		tab.style.display = 'none';
		justDownLoadTabArrayIndex = justDownLoadTabArrayIndex + n;
		if (justDownLoadTabArray[justDownLoadTabArrayIndex] === 'waitTab') {
			document.getElementById(justDownLoadTabArray[justDownLoadTabArrayIndex]).style.display = 'none';
			justDownLoadTabArrayIndex = justDownLoadTabArrayIndex + n;
		}
		showTabFromIndex(justDownLoadTabArray, justDownLoadTabArrayIndex);
	} else if (localInstallRadio.checked) {
		let tab = document.getElementById(localInstallTabArray[localInstallTabArrayIndex]);
		tab.style.display = 'none';
		localInstallTabArrayIndex = localInstallTabArrayIndex + n;
		showTabFromIndex(localInstallTabArray, localInstallTabArrayIndex);
	}
}
function nextPrev(n) {
	// This function will figure out which tab to display
	// let x = document.getElementsByClassName('tab');
	// Exit the function if any field in the current tab is invalid:
	// if (n == 1 && !validateForm()) return false;
	// if (n < 1) return false;
	//TODO 下一步校验
	//跳过
	if (notNowRadio.checked) {
		justDownLoadTabArrayIndex = 0;
		localInstallTabArrayIndex = 0;
		console.log('skipAll');
		logger.info("跳过(我自己配置)");
		ipcRenderer.send('kylinide.installWizard.ok');
		removeAllListeners();
		return;
	} else if (onlineInstallRadio.checked) {
		justDownLoadTabArrayIndex = 0;
		localInstallTabArrayIndex = 0;
		console.log("onlineInstallArrayIndex:" + onlineInstallTabArrayIndex);
		if (onlineInstallTabArray[onlineInstallTabArrayIndex] === "onlineInstallTab1") {
			//获取radio的值
			let select = "local";
			if (document.getElementById('onlineUpdateConfig') !== null && document.getElementById("onlineUpdateConfig").checked) {
				select = "update"
			}
			const data = {
				type: "configSelect",
				select: select
			}
			ipcRenderer.send('kylinide.installWizard.init', data);
		} else if (onlineInstallTabArray[onlineInstallTabArrayIndex] === "onlineInstallTab2") {
			const data = {
				type: "configGetValue",
			}
			ipcRenderer.send('kylinide.installWizard.init', data);
		} else if (onlineInstallTabArray[onlineInstallTabArrayIndex] === "onlineInstallTab3") {
			const checkboxForm = document.getElementById("checkboxForm");
			// 获取所有选中的复选框
			const selectedCheckboxes = checkboxForm.querySelectorAll('input[type="checkbox"]:checked');
			const checkSelectedValues = [];
			extInstallState.clear();
			extDownloadDoneCounter = 0;
			extInstallDoneCounter = 0;
			progressNum = 0;
			//去重
			console.log("selectedCheckboxes.length:" + selectedCheckboxes.length);

			for (const val of depList) {
				extInstallState.set(val, 0);
			}

			for (const val of extList) {
				extInstallState.set(val, 0);
			}

			for (let obj of scriptList) {
				if (obj["file_name"]) {
					extInstallState.set(obj["file_name"], 0);
				}
			}

			console.log("extInstallState.size" + extInstallState.size);
			if (selectedCheckboxes) {
				// 遍历选中的复选框，并将它们的值添加到数组中
				selectedCheckboxes.forEach(function (checkbox) {
					if (checkbox.value != "JavaScript_key")
						checkSelectedValues.push(checkbox.value);
				});
				logger.info("config:checkbox choice:" + checkSelectedValues);
			}

			document.getElementsByClassName("download-view")[0].value = 0;
			document.getElementsByClassName("progress-download")[0].innerHTML = "插件下载进度:0%";
			document.getElementsByClassName("install-view")[0].value = 0;
			document.getElementsByClassName("progress-install")[0].innerHTML = "插件安装进度:0%";

			document.getElementsByClassName("progress-view")[0].value = 0;
			document.getElementsByClassName("progressinfo")[0].innerHTML = "安装进度:0%";

			if (depList.length === 0) {
				let cname = document.getElementsByClassName("pkg-install-view")[0];
				if (cname) {
					document.getElementsByClassName("pkg-progress-install")[0].innerHTML = " ";
					cname.className = "grey-progress-view";
				}
				document.getElementsByClassName("grey-progress-view")[0].value = 0;
				// document.getElementsByClassName("pkg-progress-install")[0].style = "display: inline-block; background-color: gray;";
			}
			else {
				let cname = document.getElementsByClassName("pkg-install-view")[0];
				if (!cname) {
					document.getElementsByClassName("grey-progress-view")[0].className = "pkg-install-view";
				}
				document.getElementsByClassName("pkg-install-view")[0].value = 0;
				document.getElementsByClassName("pkg-progress-install")[0].innerHTML = "软件安装进度:0%";
			}

			let extPreElement = document.getElementById("extInstallLogPre");
			extPreElement.innerHTML = "";

			const installPkgMsg = {
				type: "installPkg",
				configList: configList,
				extList: extList,
				depList: depList,
				scriptList: scriptList
			}

			ipcRenderer.send('kylinide.installWizard.msg.process', installPkgMsg);
			ipcRenderer.send('kylinide.installWizard.init', { type: "writeJson", });
		} else if (onlineInstallTabArray[onlineInstallTabArrayIndex] === "onlineInstallTab4") {
			ipcRenderer.send('kylinide.installWizard.ok');
			removeAllListeners();
			return;
		}
		if (onlineInstallTabArrayIndex < onlineInstallTabArray.length - 1) {
			if (onlineInstallTabArrayIndex == 0) {
				logger.info("在线安装");
				removeStepIndicator();
				createStepIndicator(onlineInstallTabArray.length - 1);
				// fixStepIndicator(onlineInstallTabArray.length - 1);
				checkhttp().then(async res => {
					let preTab = document.getElementById(onlineInstallTabArray[onlineInstallTabArrayIndex]);
					preTab.style.display = 'none';
					onlineInstallTabArrayIndex = onlineInstallTabArrayIndex + n;
					showTabFromIndex(onlineInstallTabArray, onlineInstallTabArrayIndex);
					document.getElementById('nextStep').disabled = true;
					document.getElementById('prevStep').disabled = true;
					const messageData = {
						url: utils.get_g_index_url(),
						dst: updatedst,
						installconfigpath: utils.configDir(),
						type: "configVersify"
					}
					//联网检查是否有合适的文件
					ipcRenderer.send("kylinide.installWizard.init", messageData);
				}).catch(error => {
					const msg = {
						type: "internetError",
						title: "网络检查",
						message: "网络异常，无法使用在线安装"
					}
					ipcRenderer.send('kylinide.installWizard.showErrorBox', msg);
				})
			} else {
				let preTab = document.getElementById(onlineInstallTabArray[onlineInstallTabArrayIndex]);
				preTab.style.display = 'none';
				onlineInstallTabArrayIndex = onlineInstallTabArrayIndex + n;
				showTabFromIndex(onlineInstallTabArray, onlineInstallTabArrayIndex);
			}
		}
		if (onlineInstallTabArray[onlineInstallTabArrayIndex] === "onlineInstallTab3") {
			document.getElementById('nextStep').disabled = true;
			document.getElementById('nextStep').innerHTML = setLanguage('okStep');

		}
		if (onlineInstallTabArray[onlineInstallTabArrayIndex] === "onlineInstallTab4") {
			document.getElementById('prevStep').disabled = true;
			document.getElementById('nextStep').disabled = true;
			document.getElementById('nextStep').innerHTML = setLanguage('okStep');
			document.getElementById('cancel').innerText = setLanguage('cancel');
			document.getElementById('cancel').style.display = "inline";
		}
	} else if (localInstallRadio.checked) {
		justDownLoadTabArrayIndex = 0;
		if (localInstallTabArrayIndex == 0) {
			logger.info("本地安装");
		}
		if (localInstallTabArrayIndex < localInstallTabArray.length - 1) {
			let preTab = document.getElementById(localInstallTabArray[localInstallTabArrayIndex]);
			preTab.style.display = 'none';
			localInstallTabArrayIndex = localInstallTabArrayIndex + n;
			showTabFromIndex(localInstallTabArray, localInstallTabArrayIndex);
		}
	} else if (justDownloadRadio.checked) {
		console.log("justDownLoadTabArrayIndex:" + justDownLoadTabArrayIndex);
		if (justDownLoadTabArrayIndex == 0) {
			logger.info("仅下载不安装");
		}
		if (justDownLoadTabArrayIndex < justDownLoadTabArray.length - 1) {
			let preTab = document.getElementById(justDownLoadTabArray[justDownLoadTabArrayIndex]);
			preTab.style.display = 'none';
			justDownLoadTabArrayIndex = justDownLoadTabArrayIndex + n;
			showTabFromIndex(justDownLoadTabArray, justDownLoadTabArrayIndex);
		}
		if (justDownLoadTabArray[justDownLoadTabArrayIndex] === "waitTab") {
			//设置上一步与下一步按钮不可点击
			console.log("button");
			document.getElementById('nextStep').disabled = true;
			document.getElementById('prevStep').disabled = true;
			const messageData = {
				url: utils.get_g_index_url(),
				dst: updatedst,
				installconfigpath: utils.configDir(),
				type: "configVersify"
			}
			//联网检查是否有合适的文件
			ipcRenderer.send("kylinide.installWizard.justDownLoad", messageData);
		}
		else if (justDownLoadTabArray[justDownLoadTabArrayIndex] === "justDownloadTab3") {
			//获取radio的值
			let select = "local";
			if (document.getElementById('downloadUpdateConfig') !== null && document.getElementById("downloadUpdateConfig").checked) {
				select = "update"
			}
			const data = {
				type: "configSelect",
				select: select
			}
			ipcRenderer.send('kylinide.installWizard.justDownLoad', data);
		}
	}
}

function fixStepIndicator(n) {
	// This function removes the 'active' class of all steps...
	let i, x = document.getElementsByClassName('step');
	for (i = 0; i < x.length; i++) {
		x[i].className = x[i].className.replace(' active', '');
	}
	//... and adds the 'active' class on the current step:
	x[n].className += ' active';
}

function createStepIndicator(n) {
	var div = document.getElementById('indicator');
	for (let i = 0; i < n; i++) {
		// 创建一个 <span> 元素
		var span = document.createElement('span');
		span.className = 'step';
		div.appendChild(span);
	}
}

function removeStepIndicator() {
	var div = document.getElementById("indicator");
	while (div.firstChild) {
		div.removeChild(div.firstChild);
	}
}
const nextStepButton = document.getElementById("nextStep");
let configList = {};
let extList = [];
let depList = [];
let scriptList = [];

ipcRenderer.on('message-to-jsb', (event, message) => {
	configList = {};
	configList = [];
	depList = [];
	scriptList = [];
	configList = message.configList;
	extList = message.extList;
	depList = message.depList;
	scriptList = message.scriptList;
});
function setFisrtClass(depPath, jsonSelectKey) {
	var form = document.getElementById("checkboxForm");
	var depDataObject = JSON.parse(fs.readFileSync(depPath, 'utf-8'));

	let lan = getLanguage();
	let firstClass = depDataObject['first_class_list'];
	firstClassList = firstClass;

	// 创建标签列表
	let labels = [];
	let firstClassVal = [];

	if (lan == 'zh-cn') {
		labels.push('全选');
		firstClassVal.push({ key: "selectAll", val: "全选" });
	}
	else {
		labels.push('Select All');
		firstClassVal.push({ key: "selectAll", val: "Select All" });
	}

	if (firstClass.hasOwnProperty("description")) {
		let value = firstClass["description"];
		if (lan == "zh-cn" && value.hasOwnProperty("zh_cn")) {
			document.getElementById("depOutDesc").innerHTML = value["zh_cn"];
		}
		else if (lan == "en" && value.hasOwnProperty("en")) {
			document.getElementById("depOutDesc").innerHTML = value["en"];
		}
	}
	if (jsonSelectKey.length > 0) {
		if (document.getElementById('jsonSelectKey') !== null) {
			return;
		}
		const preE = document.createElement('pre');
		preE.id = "jsonSelectKey";
		let constent = "";
		let flag = 0;
		for (let i = 0; i < jsonSelectKey.length; i++) {
			console.log("json:" + firstClass[jsonSelectKey[i]]['zh_cn']);
			if (firstClass.hasOwnProperty(jsonSelectKey[i])) {
				flag++;
				constent += firstClass[jsonSelectKey[i]]['zh_cn'] + " ";
			}
		}
		if (flag > 0)
			constent += "已安装，若再次勾选，将重新安装"
		preE.textContent = constent;
		document.getElementById("depOutDesc").insertAdjacentElement("afterend", preE);
	}


	for (let key in firstClass) {
		if (firstClass.hasOwnProperty(key)) {
			let value = firstClass[key];
			if (key == "description") continue;
			if (lan == "zh-cn" && value.hasOwnProperty("zh_cn")) {
				labels.push(value["zh_cn"]);
				firstClassVal.push({ key: key, val: value["zh_cn"] });
				console.log("firstClass:" + key + ":" + value["zh_cn"]);
			}
			else if (value.hasOwnProperty("en")) {
				labels.push(value["en"]);
				firstClassVal.push({ key: key, val: value["en"] });
			}

		}
	}


	//循环创建并添加标签到表单中
	firstClassVal.forEach(function (item) {
		// 创建label元素
		var label = document.createElement("label");
		label.className = "scenarioSelection";

		// 创建checkbox元素
		var checkbox = document.createElement("input");
		checkbox.type = "checkbox";
		checkbox.value = item.key;
		checkbox.id = item.key;
		if (jsonSelectKey.indexOf(item.key) > -1) {
			checkbox.className = "checkboxselect"
		}
		else { checkbox.className = "checkbox" }
		if (checkbox.id === "JavaScript_key") {
			checkbox.checked = true;
			checkbox.disabled = true;
		}

		// 创建label文本
		var labelTextNode = document.createTextNode(" " + item.val);

		// 添加checkbox和label文本到label元素中
		label.appendChild(checkbox);
		label.appendChild(labelTextNode);

		// 添加label元素到表单中
		form.appendChild(label);
		form.appendChild(document.createElement("br"));
	});
	showDependences(depDataObject);
}

ipcRenderer.on("kylinide.installWizard.removeFileLister", (event, msg) => {
	if (msg.type == "installFile") {
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "installFile" })
	} else if (msg.type == "extFile") {
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "extFile" })
	} else if (msg.type == "pkgFile") {
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "pkgFile" })
	}
});

ipcRenderer.on('kylinide.installWizard.msg', (event, msg) => {
	//数据处理
	if (msg.type == "extStartDownload") {
		extMap = msg.extMap;
		extInstallState.set(msg.extName, 1);
	}
	else if (msg.type == "downloadExtDone") {
		extDownloadDoneCounter++;
		let num = msg.extTotal;
		let val = document.getElementsByClassName("download-view")[0].value;
		val = (extDownloadDoneCounter / num) * 100;
		val = val.toFixed(2);
		console.log(msg.extName + "下载完成" + msg.fileName + ":" + num);
		if (val > 99) val = 100;
		document.getElementsByClassName("download-view")[0].value = val;
		document.getElementsByClassName("progress-download")[0].innerHTML = "插件下载进度:" + val + "%";
		const installMsg = {
			type: "installExt",
			extList: extList,
			depList: depList,
			downloadDone: msg.fileName,
			extName: msg.extName
		};
		extInstallState.set(msg.extName, 2);
		ipcRenderer.send("kylinide.installWizard.msg.process", installMsg);
	}
	else if (msg.type == "extInstalled") {
		progressNum++;

		const extName = getKeyByValue(msg.extFileName, extMap);
		extInstallDoneCounter++;
		let num = msg.extTotal;
		let val = document.getElementsByClassName("install-view")[0].value;
		val = (extInstallDoneCounter / num) * 100;
		val = val.toFixed(2);
		if (val > 99) val = 100;
		console.log("extInstalled:  " + extName + ":" + val);

		extInstallState.set(extName, 12);
		document.getElementsByClassName("install-view")[0].value = val;
		document.getElementsByClassName("progress-install")[0].innerHTML = "插件安装进度:" + val + "%";
	}
	else if (msg.type == "extInstalledFail") {
		progressNum++;
		extInstallState.set(msg.extName, 3);
	}
	else if (msg.type == "downloadExtFail") {
		progressNum++;
		// const extName = getKeyByValue(msg.fileName, extMap);
		console.log("kylinide.installWizard.msg:downloadExtFail:  " + msg.extName);
		extInstallState.set(msg.extName, 4);
	}
	else if (msg.type == "depStartInstall") {
		if (msg.depName === "depStartInstall") {
			let preElement = document.getElementById("installLogPre");
			preElement.innerHTML = "";

			const messageData = {
				url: utils.get_g_index_url(),
				dst: utils.configDir()
			}
			//联网检查是否有合适的文件
			ipcRenderer.send("kylinide.installWizard.checkInstall", messageData);
		}
		else {
			extInstallState.set(msg.depName, 11);
		}
	}
	else if (msg.type == "depInstallSucc") {
		progressNum++;
		let num = depList.length;
		let val = document.getElementsByClassName("pkg-install-view")[0].value;

		document.getElementsByClassName("pkg-install-view")[0].value = 0;
		document.getElementsByClassName("pkg-progress-install")[0].innerHTML = "软件安装进度:0%";

		let succVal = (msg.succ / num) * 100;
		succVal = succVal.toFixed(2);
		if (succVal > val)
			val = succVal;
		if (val > 99) val = 100;
		extInstallState.set(msg.depName, 12);

		document.getElementsByClassName("pkg-install-view")[0].value = val;
		document.getElementsByClassName("pkg-progress-install")[0].innerHTML = "软件安装进度:" + val + "%";
		checkScripts(msg);
	}
	else if (msg.type === "depInstallFail") {
		progressNum++;
		extInstallState.set(msg.depName, 3);
	}
	else if (msg.type === "installLogPre") {
		let preElement = document.getElementById("installLogPre");
		let formattedDoc = preElement.innerHTML;
		formattedDoc += msg.data;
		preElement.innerHTML = formattedDoc;
		preElement.scrollTop = preElement.scrollHeight;
	}
	else if (msg.type === "extInstallLogPre") {
		let preElement = document.getElementById("extInstallLogPre");
		let formattedDoc = preElement.innerHTML;
		formattedDoc += msg.data;
		preElement.innerHTML = formattedDoc;
		preElement.scrollTop = preElement.scrollHeight;
	}
	else if (msg.type === "extDownloadInit") {
		ipcRenderer.send('kylinide.installWizard.downloadExt', {
			extAddressPath: extAddressPath,
			configList: configList
		});
	} else if (msg.type === "scriptExecFail") {
		// console.log("kylinide.installWizard.msg:scriptExecFail");
		progressNum++;
		extInstallState.set(msg.depName, 16);
	} else if (msg.type === "scriptExecSucc") {
		// console.log("kylinide.installWizard.msg:scriptExecSucc");
		progressNum++;
		extInstallState.set(msg.depName, 15);
	}
	let dTpreElement = document.getElementById("detailInstallPre");
	dTpreElement.innerHTML = '';
	let dTformattedDoc = '';


	document.getElementsByClassName("progress-view")[0].value = (progressNum / extInstallState.size) * 100;
	document.getElementsByClassName("progressinfo")[0].innerHTML = "安装进度:" + ((progressNum / extInstallState.size) * 100).toFixed(2) + "%";

	for (const [key, value] of extInstallState) {
		if (key === undefined) continue;
		switch (value) {
			case 0:
				dTformattedDoc += "<span class='startHighlight'>" + key + "准备中...</span><br>";
				break;
			case 1:
				dTformattedDoc += "<span class='startHighlight'>" + key + "开始下载</span><br>";
				break;
			case 2:
				dTformattedDoc += "<span class='downloadHighlight'>" + key + "下载完成</span><br>";
				break;
			case 3:
				dTformattedDoc += "<span class='depfailHighlight'>" + key + "安装失败</span><br>";
				break;
			case 4:
				dTformattedDoc += "<span class='depfailHighlight'>" + key + "下载失败</span><br>";
				break;
			case 11:
				dTformattedDoc += "<span class='downloadHighlight'>" + key + "开始安装</span><br>";
				break;
			case 12:
				dTformattedDoc += "<span class='installedHighlight'>" + key + "安装完成</span><br>";
				break;
			case 15:
				dTformattedDoc += "<span class='installedHighlight'>" + key + "脚本执行成功</span><br>";
				break;
			case 16:
				dTformattedDoc += "<span class='depfailHighlight'>" + key + "脚本执行失败</span><br>";
				break;
			default:
				// 处理默认情况
				break;
		}
	}
	dTpreElement.innerHTML = dTformattedDoc;

	let flag = 0;
	//检查所有处理是否已完成
	if (msg.type == "extInstalled" || msg.type == "extInstalledFail"
		|| msg.type == "downloadExtFail" || msg.type == "depInstallSucc"
		|| msg.type == "depInstallFail" || msg.type == "scriptExecFail" || msg.type == "scriptExecSucc") {
		for (const [key, value] of extInstallState) {
			if (key === undefined) continue;
			switch (value) {
				case 0: flag++;
					break;
				case 1: flag++;
					break;
				case 2:
					flag++;
					break;
				case 11:
					flag++
					break;
				default:
					// 处理默认情况
					break;
			}
		}

		if (flag === 0) {
			//检查所有的开发场景是否都安装成功
			let writeKeyJson = [];
			let preFinish = document.getElementById("finishPage");
			let showContext = "";
			showContext += "安装结束\n";

			for (let key in configList) {
				console.log("end:" + key);
				//检查某个开发场景的软件包是否全部安装成功
				let tmp = getNameFromKey(key);
				if (checkInstalledSucc(key, configList, extInstallState)) {
					writeKeyJson.push(key);
					showContext += tmp + "安装成功\n";
				} else {
					showContext += tmp + "安装失败\n";
				}
			}
			if (writeKeyJson.length > 0) {
				ipcRenderer.send("kylinide.installWizard.init", { type: "writeKey", keys: writeKeyJson });
			}
			finishFlag = 0;
			showContext += "点击结束按钮退出安装向导\n"
			preFinish.innerHTML = showContext;
			preFinish.style.display = 'block';
			document.getElementById("installLogPre").style.display = 'none';
			document.getElementById("detailInstallPre").style.display = 'none';
			document.getElementById("extInstallLogPre").style.display = 'none';

			document.getElementById("nextStep").innerText = setLanguage("finish");
			document.getElementById("nextStep").disabled = false;
			document.getElementById("cancel").disabled = true;
			logShow = 0;
			ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "extFile" });
			ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "pkgFile" });
			ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "installFile" });

		}
	}
	// preElement.scrollTop = preElement.scrollHeight;
});

ipcRenderer.on("kylinide.installWizard.Auth", (event, msg) => {
	if (msg.type == "pkgNotAuth") {
		finishFlag = 0;
		let preFinish = document.getElementById("finishPage");
		let showContext = preFinish.innerHTML;
		showContext += "授权失败，结束安装\n";
		showContext += "点击结束按钮退出安装向导\n"
		preFinish.innerHTML = showContext;
		preFinish.style.display = 'block';
		document.getElementById("installLogPre").style.display = 'none';
		document.getElementById("detailInstallPre").style.display = 'none';
		document.getElementById("extInstallLogPre").style.display = 'none';

		document.getElementById("nextStep").innerText = setLanguage("finish");
		document.getElementById("nextStep").disabled = false;
		document.getElementById("cancel").disabled = true;
		logShow = 0;
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "extFile" });
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "pkgFile" });
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "installFile" });
		removeAllListeners();
	}
});
ipcRenderer.on("kylinide.installWizard.cancelinstall", (event, msg) => {
	if (msg.type == "cancelinstall") {
		finishFlag = 0;
		let preFinish = document.getElementById("finishPage");
		let showContext = '';
		showContext += "取消安装\n";
		showContext += "点击结束按钮退出安装向导\n"
		preFinish.innerHTML = showContext;
		preFinish.style.display = 'block';
		document.getElementById("installLogPre").style.display = 'none';
		document.getElementById("detailInstallPre").style.display = 'none';
		document.getElementById("extInstallLogPre").style.display = 'none';

		document.getElementById("nextStep").innerText = setLanguage("finish");
		document.getElementById("nextStep").disabled = false;
		document.getElementById("cancel").disabled = true;
		logShow = 0;
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "extFile" });
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "pkgFile" });
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "installFile" });
		removeAllListeners();
	}
})

//根据key值获取value
function getNameFromKey(key) {
	let name = '';
	if (firstClassList.hasOwnProperty(key)) {
		name = firstClassList[key]['zh_cn'];
	}
	return name;
}
function checkInstalledSucc(key, configList, extInstallState) {
	let flagjson = 0;
	for (let depname in configList[key]['pkg-list']['deb']) {
		if (extInstallState.get(depname) != 12) {
			flagjson++;
		}
	}
	//检查某个开发场景的插件列表是否全部安装成功
	for (let extname of configList[key]['ext-list']) {
		if (extInstallState.get(extname) != 12) {
			flagjson++;
		}
	}
	//检查某个开发场景的脚本是否全部安装成功
	for (let scriptname of configList[key]['script-list']) {
		if (extInstallState.get(scriptname['file_name']) != 15) {
			flagjson++;
		}
	}
	if (flagjson > 0) {
		return false;
	} else {
		return true;
	}
}




//显示系统信息
function readOSInfo(os) {
	console.log('readosinf');
	const parentdiv = document.getElementById('osInfo')
	const parentdivshow = document.getElementById('osInfoShow');
	parentdiv.innerHTML = "";
	parentdivshow.innerHTML = "";
	const kyinfoPath = '/etc/.kyinfo';
	const osReleasePath = '/etc/os-release';
	let osinfo;
	if (!os) {
		osinfo = `<h3>操作系统信息</h3><p>操作系统检测脚本运行失败，未成功检测到操作系统类型</p>`
	} else {
		osinfo = `<h3>操作系统信息</h3><p>已检测到当前操作系统信息为：<span style="color:#1177BB;">${os}</span></p>`;
	}
	parentdiv.innerHTML = osinfo;

	let data = "";
	let osdiv;
	if (fs.existsSync(kyinfoPath)) {
		try {
			osdiv = `<p>判断依据:</p><p>cat /etc/.kyinfo</p>`
			data = fs.readFileSync(kyinfoPath, 'utf8');
			data = data.replace(/\n/g, '<br>');
		} catch (err) {
		}
	} else if (fs.existsSync(osReleasePath)) {
		try {
			osdiv = "操作系统信息:cat /etc/os-release"
			data = fs.readFileSync(osReleasePath, 'utf8');
			data = data.replace(/\n/g, '<br>');
		} catch (err) { }
	}
	if (osdiv == "" && data == "") {
		parentdivshow.innerHTML = "读取操作系统信息失败";
	} else {
		parentdivshow.innerHTML = `${osdiv}<p>${data}</p>`;
	}
}

function getKeyByValue(value, map) {
	const entries = Object.entries(map);
	for (const [key, val] of entries) {
		if (val === value) {
			return key;
		}
	}
	return undefined;
}

function getDataDir() {
	const currentD = new Date().getTime();
	// const datasttr = currentD.toLocaleDateString();
	// let name = datasttr.replace(/\//g, '')
	return currentD;
}

//读取使用的配置文件的存放路径
// 1.如果没有selectfile.json，则使用的为/usr/share、...目录下的配置文件
// 2.如果存在selectfile.json，则使用的配置文件地址为selecDir的值
function localConfigPath() {
	let localConfigDir = path.join(path.dirname(__dirname), "../../../../../../config/");
	if (fs.existsSync(utils.configDir() + '/' + 'selectFile.json')) {
		let { selectDir } = require(utils.configDir() + '/' + 'selectFile.json');
		if (selectDir)
			return selectDir;
	}
	return localConfigDir;
}
//发送执行脚本请求
function checkScripts(msg) {
	for (let obj of scriptList) {
		if (obj["postin"] == msg.depName) {
			const installMsg = {
				type: "installScript",
				extList: extList,
				depList: depList,
				script: obj,
				dst: utils.configDir()
			};
			ipcRenderer.send("kylinide.installWizard.msg.process", installMsg);
		}
	}
}

function removeAllListeners() {
	ipcRenderer.removeAllListeners('init-data');
	ipcRenderer.removeAllListeners('kylinide.installWizard.init');
	ipcRenderer.removeAllListeners('kylinide.installWizard.justDownLoad');
	ipcRenderer.removeAllListeners('message-to-jsb');
	ipcRenderer.removeAllListeners('kylinide.installWizard.msg');
	ipcRenderer.removeAllListeners('kylinide.installWizard.removeFileLister');
	ipcRenderer.removeAllListeners('kylinide.installWizard.Auth');
	ipcRenderer.removeAllListeners('kylinide.installWizard.cancelinstall');
}
